<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			title="订单批号"
			width="1000px"
			:show-content-loading="showLoading"
			:custom-btn-loading="confirmBtnLoading"
			:confirm-btn-loading="saveBtnLoading"
			:show-confirm-btn="false"
			:show-cancel-btn="false"
			:show-close-btn="true"
			@on-visible-change="onVisibleChange"
			@on-close="onVisibleChange"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" :show-message="false">
				<jk-divider-card ref="box1" placement="center" title="订单信息" class="margin-bottom-10">
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="生产订单号">
								<span class="read-only-2">{{ ruleForm.code }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="品种">
								<span class="read-only-2">{{ ruleForm.productName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="支数">
								<span class="read-only-2">{{ ruleForm.yarnCount }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="生产数量">
								<span class="read-only-2">{{ ruleForm.orderQty }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="优先级">
								<span class="read-only-2">{{ ruleForm.priorityName || '无' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="交期">
								<span class="read-only-2">{{ `${ruleForm.deliveryDateTo}` }}</span>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-divider-card>
				<div>
					<!--<el-button class="margin-bottom-4" type="primary" size="mini" icon="el-icon-plus" @click="onAddBtn">生产工序</el-button>-->
					<el-tag class="margin-bottom-4" effect="plain" size="mini"><span class="el-icon-tickets item-gap"></span>批号明细</el-tag>
					<jk-table ref="jkTable" :loading="tableLoading" :data="tableData" :height="dialogTableHeight - 80">
						<vxe-column title="批号" field="code" align="left" :min-width="150">
							<template slot-scope="scope">
								<span v-if="!scope.row.isEdit">{{ scope.row.batchCode }}</span>
								<jk-select v-else v-model="scope.row.batchId" :option-list="batchList" :disabled="scope.row.auditState >= 3" value-key-name="batchId" label-key-name="batchCode" placeholder="批号" :clearable="false" size="mini" class="width-100-percent"></jk-select>
							</template>
						</vxe-column>
						<vxe-column title="生产通知单" field="code" align="left" :min-width="140">
							<!--<template slot-scope="scope">
								<span :class="scope.row.code ? 'link-style' : ''" @click="onJump(scope.row)">{{ scope.row.code || '系统自动生成' }}</span>
							</template>-->
						</vxe-column>
						<vxe-column title="排产数量" align="right" field="productionQty" :min-width="100">
							<template slot-scope="scope">
								<span v-if="!scope.row.isEdit">{{ scope.row.productionQty }}</span>
								<jk-number-input v-else v-model="scope.row.productionQty" :disabled="scope.row.auditState >= 3" size="mini" placeholder=""></jk-number-input>
							</template>
						</vxe-column>
						<vxe-column title="工序" field="code" align="left" :width="90">
							<template slot-scope="scope">
								<span v-if="!scope.row.isEdit">{{ scope.row.processName }}</span>
								<jk-select v-else v-model="scope.row.processCode" :option-list="processList" :clearable="false" value-key-name="code" :disabled="scope.row.auditState >= 3" placeholder="工序" size="mini"></jk-select>
							</template>
						</vxe-column>
						<vxe-column title="生产区域" align="left" field="shiftName" :width="140">
							<template slot-scope="scope">
								<span v-if="!scope.row.isEdit">{{ scope.row.workshopName }}</span>
								<jk-select v-else v-model="scope.row.workshopId" :option-list="workshopList" :clearable="false" :disabled="scope.row.auditState >= 3" placeholder="生产区域" size="mini"></jk-select>
							</template>
						</vxe-column>
						<vxe-column title="状态" align="left" field="auditState" :width="90">
							<template slot-scope="scope">
								<jk-state-bar :state="scope.row.auditState" :state-list="noticeStateList"></jk-state-bar>
							</template>
						</vxe-column>
						<vxe-column title="操作" align="center" field="operation" :width="220">
							<template slot-scope="scope">
								<div class="flex-center">
									<el-popconfirm title="确定'生产完成'吗？" @confirm="onStateTrue(scope.row)">
										<jk-button slot="reference" icon="el-icon-finished" style="margin-right: 3px" :disabled="scope.row.auditState === 3" type="success" size="mini">生产完成</jk-button>
									</el-popconfirm>
									<el-popconfirm title="确定'撤销完成'吗？" @confirm="onStateFalse(scope.row)">
										<jk-button slot="reference" icon="el-icon-circle-close" :disabled="scope.row.auditState < 3" type="warning" size="mini">撤销完成</jk-button>
									</el-popconfirm>
								</div>
							</template>
						</vxe-column>
					</jk-table>
				</div>
			</el-form>
		</jk-dialog>
		<notice-order-dialog
			page-type="edit"
			:data-id="noticeId"
			:dialog-state="noticeOrderDialogState"
			@on-visible-change="onVisibleChangeOfNoticeOrderDialogState"
			@on-confirm="onConfirmBtnOfNoticeOrderDialogState"
		></notice-order-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { productionPrdOrderGet } from '../../../../api/production/order';
    import {
        productionProcessPrdNoticeCreate, productionProcessPrdNoticeDelete, productionProcessPrdNoticeGet,
        productionProcessPrdNoticePage,
        productionProcessPrdNoticeUpdate,
        productionProcessPrdNoticeComplete,
        productionProcessPrdNoticeClearComplete
    } from '../../../../api/production/xsNotice';
    import { clearRedundancyKey, formatDate, tipsBar } from '../../../../utils/jk/jk-tool';
    import { noticeStateList } from '../../../../utils/jk/status-option-list';
    import noticeOrderDialog from './notice-order-dialog';
    export default {
        components: {
            noticeOrderDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [Number, String],
                default: null
            }
        },
        mixins: [calHeight],
        data() {
            return {
                noticeId: null,
                noticeOrderDialogState: false,
                noticeStateList: noticeStateList,
                tableLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveBtnLoading: false,
                ruleForm: {},
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    batchId: [{ required: true, trigger: 'change' }]
                },
                batchList: [],
                processList: [],
                tableData: [],
                editRow: {},
                defaultProcessCode: '',
                defaultRowInfo: {
                    workshopId: null,
                    workshopCode: '',
                    batchId: null,
                    batchCode: '',
                    workshopName: '',
                    productionQty: null,
                    code: '',
                    rowLoading: false,
                    auditState: null
                }
            };
        },
        methods: {
            onStateTrue(value) {
                productionProcessPrdNoticeComplete({ id: value.id }).then(res => {
                    if (res.data.status === 200) {
                        this.getDependentData();
                        this.$emit('on-refresh');
                    }
                });
            },
            onStateFalse(value) {
                productionProcessPrdNoticeClearComplete({ id: value.id }).then(res => {
                    if (res.data.status === 200) {
                        this.getDependentData();
                        this.$emit('on-refresh');
                    }
                });
            },
            onConfirmBtnOfNoticeOrderDialogState() {
                this.noticeOrderDialogState = false;
            },
            onVisibleChangeOfNoticeOrderDialogState(e) {
                this.noticeOrderDialogState = e;
            },
            onJump(row) {
                this.$emit('on-visible-change', false);
                this.$nextTick(() => {
                    this.noticeId = row.id;
                    this.noticeOrderDialogState = true;
                });
                /* if (!row.id) return;
                this.$toOtherRouter({
                    name: 'editProductionNoticeOrder',
                    query: {
                        id: row.id
                    }
                });*/
            },
            onToggleEditBtn(scope) {
                this.$set(this.tableData[scope.rowIndex], 'isEdit', !scope.row.isEdit);
            },
            onDeleteBtn(scope) {
                if (scope.row.id) {
                    this.$confirm('该通知单已创建, 确认删除吗?', { type: 'warning' }).then(() => {
                        productionProcessPrdNoticeDelete({ id: scope.row.id }).then(res => {
                            if (res.data.status === 200) {
                                this.$emit('on-finish');
                                this.getNoticeListByOrderRequest();
                            }
                        });
                    });
                } else {
                    this.tableData.splice(scope.rowIndex, 1);
                }
            },
            onAddBtn() {
                const item = JSON.parse(JSON.stringify(this.defaultRowInfo));
                item.productionQty = this.ruleForm.orderQty;
                item.workshopId = this.$store.state.user.userWorkshop.defaultWorkshopId;
                item.batchId = this.batchList && this.batchList.length ? this.batchList[0].batchId : null;
                item.processCode = this.defaultProcessCode;
                item.auditState = 0;
                item.isEdit = true;
                this.tableData.push(item);
            },
            getParamData(data) {
                let params = JSON.parse(JSON.stringify(data));
                // 订单和品种信息
                params.productOrderId = this.ruleForm.id;
                params.productOrderCode = this.ruleForm.code;
                params.productId = this.ruleForm.productId;
                params.productCode = this.ruleForm.productCode;
                params.productName = this.ruleForm.productName;
                params.productModels = this.ruleForm.productModels;
                params.productionQty = data.productionQty || 0;
                params.belongDate = params.belongDate || formatDate(Date.now());
                const processItem = this.processList.find(x => x.code === data.processCode) || {};
                params.processId = processItem.id;
                params.processCode = processItem.code;
                params.processName = processItem.name;

                const workshopItem = this.workshopList.find(x => x.id === data.workshopId) || {};
                params.workshopId = workshopItem.id;
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;

                const batchItem = this.batchList.find(x => x.batchId === data.batchId) || {};
                params.batchId = batchItem.batchId;
                params.batchCode = batchItem.batchCode;
                // 下达细纱通知单时，默认纸管颜色
                if (params.processCode && params.processCode.toUpperCase() === 'XS') {
                    // 纸管
                    params.paperTubeList = batchItem.paperTubeList;
                }

                delete params.productOrder;
                delete params.rowLoading;
                delete params.isEdit;
                params = clearRedundancyKey(params);
                return params;
            },
            onConfirmBtn(scope) {
                if (scope.row.workshopId && scope.row.batchId) {
                    let params = {};
                    if (scope.row.id) {
                        productionProcessPrdNoticeGet({ id: scope.row.id }).then(res => {
                            if (res.data.status === 200) {
                                const params = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};

                                params.productionQty = scope.row.productionQty || 0;
                                params.belongDate = params.belongDate || formatDate(Date.now());
                                const processItem = this.processList.find(x => x.code === scope.row.processCode) || {};
                                params.processId = processItem.id;
                                params.processCode = processItem.code;
                                params.processName = processItem.name;

                                const workshopItem = this.workshopList.find(x => x.id === scope.row.workshopId) || {};
                                params.workshopId = workshopItem.id;
                                params.workshopCode = workshopItem.code;
                                params.workshopName = workshopItem.name;

                                const batchItem = this.batchList.find(x => x.batchId === scope.row.batchId) || {};
                                params.batchId = batchItem.batchId;
                                params.batchCode = batchItem.batchCode;
                                this.saveRequest(scope, params);
                            }
                        });
                    } else {
                        params = this.getParamData(scope.row);
                        this.saveRequest(scope, params);
                    }
                } else {
                    this.$tipsBar(this, 'validator');
                }
            },
            saveRequest(scope, params) {
                const api = scope.row.id ? productionProcessPrdNoticeUpdate : productionProcessPrdNoticeCreate;
                this.$set(this.tableData[scope.rowIndex], 'rowLoading', true);
                api(params).then(res => {
                    this.$set(this.tableData[scope.rowIndex], 'rowLoading', false);
                    if (res.data.status === 200) {
                        tipsBar(this, 'save');
                        this.$emit('on-finish');
                        this.getNoticeListByOrderRequest();
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            transferData(res) {
                const resData = res ? JSON.parse(JSON.stringify(res)) : {};
                const params = {
                    ...resData,
                    batchId: null,
                    batchCode: null,
                    workshopId: null,
                    workshopCode: null,
                    workshopName: null
                };
                this.batchList = resData.productOrderBatchList;
                return params;
            },
            getDetailRequest() {
                return productionPrdOrderGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = this.transferData(res.data.res);
                        this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    }
                });
            },
            getNoticeListByOrderRequest() {
                return productionProcessPrdNoticePage({
                    productOrderId: this.dataId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res.map(x => {
                            x.rowLoading = false;
                            x.isEdit = false;
                            return x;
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                this.defaultProcessCode = this.$store.state.user.userProcess.defaultProcessCode || '';
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (this.dataId) await this.getDetailRequest();
                await this.getNoticeListByOrderRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
